import React, { Component } from 'react';
import './login.css';
import {Link} from 'react-router-dom';
import './component/Title';
import Title from './component/Title'
import Slogan from './component/Slogan';
import UsernameInput from './component/UsernameInput';
import PasswordInput from './component/PasswordInput';
import 'antd-mobile/dist/antd-mobile.css';
import 'antd-mobile/lib/toast/style/index.css';
import { Toast } from 'antd-mobile';
import {login} from '../../Lib/Http';

class Login extends Component {
    
    constructor(props){
        super(props);

        this.state={
            username:'',
            password:''
        }

    }

    componentDidMount(){

        let that = this;
        let _b_url = that.props.history.location.pathname;
        window._hmt.push(['_trackPageview', _b_url]);
    }

    //设置用户名
    setUserName(value){
        this.setState({
            username:value
        });
    }

    //设置密码
    setPassword(value){
        this.setState({
            password:value
        });
    }


    //登录
    login(e){
        let username = this.state.username;
        let password = this.state.password;

        if(username.length <= 0){
            Toast.info('用户名不能为空', 1)
            return;
        }

        if(password.length <= 0){
            Toast.info('密码不能为空', 1)
            return;
        }

        Toast.loading('Loading...', 10);


        login(username, password, (response)=>{
            Toast.hide();

            this.props.history.push('/');

        }, function(error){
            Toast.hide();
            
            if(error.response === undefined){
                return;
            }

            if(error.response.data.error === 'invalid_credentials'){
                Toast.info('用户名或密码错误');
            }

        });

        
    }

    render(){
        return (
            <div className='root background-white'>
                
                <Title title='登录' />

                <div className='auth-login-form-box'>
                    <div className='auth-login-form-wrapper'>
                        <Slogan />

                        <UsernameInput getValue={this.setUserName.bind(this)} />

                        <PasswordInput plaintext={1}
                            getValue={this.setPassword.bind(this)}
                        />

                        <div className='forget-password-box'>
                            <Link className='forget-password' to='/register'>注册</Link>
                        </div>

                        <div onClick={(e)=>this.login(e)} className='login-button'>
                            登录
                        </div>

                    </div>
                </div>

            </div>
        );
    }

}

export default Login;